<?php

namespace App\Admin\Controllers;

use App;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Services\MyPermission;
use App\Models\WechatUser;
use App\Models\TestingUserRecord;
use App\Models\TestingDetail;
use App\Models\TestingItem;
use Illuminate\Http\Request;
use TestingXjbHelper;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Table;
use WechatUserService;
use TestingDetailService;
use App\Services\IdEncryptService;
class DecreaseWeightController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Request $request)
    {
        $appid = empty($request->input('appid')) ? "" : base64_decode($request->input('appid'));
        $tid=empty($request->input('tid'))? 21 : $request->input('tid');
        return Admin::content(function (Content $content) use($tid,$appid) {
            $content->header(trans('backend.user_record.title.list'));
            $content->body($this->grid($tid,$appid));
        });
    }

    /**
     * Edit interface.
     * @param $id
     * @return Content
     */

    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header();
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(TestingUserRecord::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->display('nick_name', trans('backend.user_record.column.nick_name'));
            $form->display('testing_name',trans('backend.user_record.column.tidtitle'));
            $form->text('score',trans('backend.user_record.column.score'));
            $form->text('conclusion', trans('backend.user_record.column.conclusion'));
        });
    }




    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($tid,$appid)
    {
        return Admin::grid(TestingUserRecord::class, function (Grid $grid) use($tid,$appid) {
            $grid->model()->decreaseWeight($tid,$appid);
            $grid->model()->orderBy('id', 'desc');
            $this->buildGrid($grid,$tid,$appid);
        });
    }




    public function buildGrid($grid,$tid,$appid){
        $grid->id('ID')->sortable();
        $grid->nick_name(trans('backend.user_record.column.nick_name'));
        $grid->testing_name(trans('backend.user_record.column.tidtitle'));
        $grid->score(trans('backend.user_record.column.score'));
        $grid->conclusion(trans('backend.user_record.column.conclusion'));
        $grid->created_at(trans('backend.user_record.column.creat_at'));
        $grid->rows(function($row)use($appid){
            if(MyPermission::check('edit') || MyPermission::check('delete')) {
                if(MyPermission::check('edit') && MyPermission::check('delete')){
                    $row->actions('edit|delete');
                }elseif(MyPermission::check('edit') && !MyPermission::check('delete')){
                    $row->actions('edit');
                }elseif(!MyPermission::check('edit') && MyPermission::check('delete')){
                    $row->actions('delete');
                }
            }else{
                $row->actions('');
            }

            $row->actions()->add(function ($row)use($appid) {
                if($appid){
                    return "<a href='/admin/testing/decrease/user/info/{$row->id}/{$row->uid}/{$row->tid}/".base64_encode($appid)."'><i class='fa fa-eye'></i></a>";
                }else{
                    return "<a href='/admin/testing/decrease/info/{$row->id}/{$row->tid}/'><i class='fa fa-eye'></i></a>";
                }
            });

        });

        $grid->disablePerPageSelector();
        $grid->filter(function ($filter) use($tid){
            $filter->disableIdFilter();
            $filter->useModal();
//            $filter->is('uid',trans('backend.user_record.column.nick_name'))->select(WechatUserService::options()->pluck('nick_name','uid'));
            $filter->is('tid',$tid);
            $filter->like('nick_name',trans('backend.user_record.column.nick_name'));
        });
        $grid->disableExport();
        $grid->disableCreation();
        if(!MyPermission::check('delete')){
            $grid->disableBatchDeletion();
        }
    }

    public function middleinfo($id,$tid){
        return Admin::content(function (Content $content) use ($id,$tid) {
            $content->header(trans('backend.user_record.title.infor'));
            $time="2017-02-15 22:00:00";

            $res= TestingUserRecord::where(['id'=>$id,'tid'=>$tid])->first()->toarray();

            //根基提交时间判断
            if($res['created_at'] >= $time){
                $contents = $this->formatConclusionOne($res);
            }else{
                $contents = $this->formatConclusionTwo($res);
            }
            $str = "";
            foreach($contents as $k => $v){
                $str =$str.$v."</br>";
            }
            $box = new Box('S-轻体测评结论',$str);
            $content->row($box->style('info')->solid());
        });
    }

    public function info($id,$tid)
    {
        return Admin::content(function (Content $content) use ($id,$tid) {
            $content->header(trans('backend.user_record.title.infor'));
            $time="2017-02-15 22:00:00";

            $res= TestingUserRecord::where(['id'=>$id,'tid'=>$tid])->first()->toarray();

            //根基提交时间判断
            if($res['created_at'] >= $time){
                $result = $this->formate($res,$tid);
            }else{
                $result = $this->formate($res,$tid,1);
            }
            $title = TestingDetail::where('id',$tid)->value('name');
            $headers = ['题号','测评题目','提交答案'];
            $answerstr = [];
            foreach($result as $k=>$v){
                $answer = implode(',',$v);
                $answerArr = explode(',',$answer);
                $answerstr[$k]=$answerArr;
            }
            $table = new Table($headers,$answerstr);
            $content->row((new Box($title,$table))->style('info')->solid());
        });
    }

    /**题目列表(最新版题目)
     * @param $res
     * @param $tid
     * @return array
     */
    protected function formate($res,$tid,$type=null){
        $answerArray =  TestingXjbHelper::strToArr($res['answers']);
        $indexArr = [];
        foreach($answerArray as $k => $v){
            if($type){
                $result = TestingItem::select('title','question_type')->where(['testing_id'=>20,'index'=>$v['index']])->first()->toarray();
            }else{
                $result = TestingItem::select('title','question_type')->where(['testing_id'=>$tid,'index'=>$v['index']])->first()->toarray();
            }
            $indexArr[$k]['index'] = $v['index'];
            $indexArr[$k]['title'] = $result['title'];
            //$indexArr[$k]['answer'] =$this->formateWeight($v['answer']);
            $indexArr[$k]['answer']= $v['answer'];
        }
        return $indexArr;
    }

    protected function formateWeight($str){
        $arr = explode("|||",$str);
        if(count($arr)>1){
            $str = implode(',',$arr);
        }
        return $str;
    }

    /**格式化获取结论(最新版题目)
     */
    public function formatConclusionOne($res){
        $answerArray =  TestingXjbHelper::strToArr($res['final_answers']);
        $data = [];
        $con_one=$this->getValue($answerArray,1,'answer');
        $con_two=$this->getValue($answerArray,2,'answer');
        $con_fiveteen=$this->getValue($answerArray,19,'answer');
        $name = $this->getValue($answerArray,20,'answer');
        $myIndex = $this->getValue($answerArray,25,'weight');
        $lowestHealth = "18.5*$con_one*$con_one/10000";
        $health = number_format(eval("return $lowestHealth;"),2);
        $lowestHealthstr = "最低健康体重：".$health."Kg";
        array_push($data,$lowestHealthstr);
        $weight = $con_two - $con_fiveteen;
        $goalweightstr = "目标体重：".$weight."Kg";
        array_push($data,$goalweightstr);
        $advinceweight = $con_two - number_format(eval("return $lowestHealth;"),2);
        $advinceweightstr = "建议减重目标：".$advinceweight."Kg";
        array_push($data,$advinceweightstr);
        $bmi =$this->getValue($answerArray,21,'weight');
        $BMIstr = "BMI：".number_format($bmi,2);
        array_push($data,$BMIstr);
        $con_twelve = $this->getValue($answerArray,12,'answer');
        if($bmi<18.5 && strpos($con_twelve,'重')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*40;
        }elseif($bmi<18.5 && strpos($con_twelve,'出差')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*40;
        }elseif($bmi<18.5 && strpos($con_twelve,'重') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*35;
        }elseif($bmi<18.5 && strpos($con_twelve,'出差') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*35;
        }elseif($bmi>=18.5 && strpos($con_twelve,'重')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*30;
        }elseif($bmi>=18.5 && strpos($con_twelve,'出差')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*30;
        }elseif($bmi>=18.5 && strpos($con_twelve,'重') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*25;
        }elseif($bmi>=18.5 && strpos($con_twelve,'出差') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*25;
        }
        $heat = eval("return $con_twelvestr;");
        $heatstr = "每日所需热量：".$heat."   卡路里";
        array_push($data,$heatstr);
        if($con_fiveteen<=4){
            $k=0.9*$heat;
        }elseif(4<$con_fiveteen && $con_fiveteen<=7){
            $k=0.85*$heat;
        }elseif(7<$con_fiveteen && $con_fiveteen<=10){
            $k=0.8*$heat;
        }elseif(10<$con_fiveteen && $con_fiveteen<=13){
            $k=0.75*$heat;
        }elseif(13<$con_fiveteen){
            $k=0.70*$heat;
        }
        $everyheatstr = "每日膳食热量：".eval("return $k;")."  卡路里";
        array_push($data,$everyheatstr);
        $eleven = $this->getValue($answerArray,11,'weight');
            if($eleven == -1){
                $p="P：1";
            }elseif($eleven == 1){
                $p="P：2";
            }elseif($eleven == 2){
                $p="P：3";
            }else{
                $p="P：0";
            }
        array_push($data,$p);
        $eight = $this->getValue($answerArray,8,'weight');
        $eightstr =  $this->getValue($answerArray,8,'answer');
        if($eight == 1){
            $d="D：1";
        }elseif($eight == -1){
            $d="D：2";
        }elseif($eight == 2){
            $d="D：3";
        }else{
            $d="D：0";
        }
        array_push($data,$d);
        /*$proportion = $con_fiveteen/$con_two*100;
        if($weight > $health  && $myIndex > 0){
            $conclusion = $name."，你好！根据你的测评，你的21天减重目标是".$con_fiveteen."kg，相当于现有体重的".number_format(eval("return $proportion;"),2)."%。研究显示，超重和肥胖患者体重如果能成功减轻5%-10%，可以提高多项身体健康指标，大大降低多种慢性疾病的患病风险。为了健康，为了美，请你加油哦。现在我们先来看看你的测评分析。";
            array_push($data,$conclusion);
        }
        if($weight < $health  && $myIndex > 0){
            $conclusion = $name."，你好！根据你的测评，你的21天减重目标是".$con_fiveteen." kg，超过了你的健康减重范围，我们建议尝试".$advinceweight." kg作为你的减重目标。为了健康，为了美，请你加油哦。现在我们先来看看你的测评分析。";
            array_push($data,$conclusion);
        }
        if(count($data)>=7){
            array_unshift($data, array_pop($data));
        }*/
        return $data;
    }

    /**格式化获取结论(老版题目)
     */
    protected function formatConclusionTwo($res){
        $answerArray =  TestingXjbHelper::strToArr($res['final_answers']);
        $data = [];
        $con_one=$this->getValue($answerArray,1,'answer');
        $con_two=$this->getValue($answerArray,2,'answer');
        $con_fiveteen=$this->getValue($answerArray,19,'answer');
        $name = $this->getValue($answerArray,20,'answer');
        $myIndex = $this->getValue($answerArray,25,'weight');
        $lowestHealth = "18.5*$con_one*$con_one/10000";
        $health = number_format(eval("return $lowestHealth;"),2);
        $lowestHealthstr = "最低健康体重：".$health."Kg";
        array_push($data,$lowestHealthstr);
        $weight = $con_two - $con_fiveteen;
        $goalweightstr = "目标体重：".$weight."Kg";
        array_push($data,$goalweightstr);
        $advinceweight = $con_two - number_format(eval("return $lowestHealth;"),2);
        $advinceweightstr = "建议减重目标：".$advinceweight."Kg";
        array_push($data,$advinceweightstr);
        $bmi =$this->getValue($answerArray,21,'weight');
        $BMIstr = "BMI：".number_format($bmi,2);
        array_push($data,$BMIstr);
        $con_twelve = $this->getValue($answerArray,12,'answer');
        if($bmi<18.5 && strpos($con_twelve,'重')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*40;
        }elseif($bmi<18.5 && strpos($con_twelve,'出差')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*40;
        }elseif($bmi<18.5 && strpos($con_twelve,'重') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*35;
        }elseif($bmi<18.5 && strpos($con_twelve,'出差') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*35;
        }elseif($bmi>=18.5 && strpos($con_twelve,'重')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*30;
        }elseif($bmi>=18.5 && strpos($con_twelve,'出差')!== false){
            $con_twelvestr = ($con_one/100-1.05)*100*30;
        }elseif($bmi>=18.5 && strpos($con_twelve,'重') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*25;
        }elseif($bmi>=18.5 && strpos($con_twelve,'出差') == false){
            $con_twelvestr = ($con_one/100-1.05)*100*25;
        }
        $heat = eval("return $con_twelvestr;");
        $heatstr = "每日所需热量：".$heat."   卡路里";
        array_push($data,$heatstr);
        if($con_fiveteen<=4){
            $k=0.9*$heat;
        }elseif(4<$con_fiveteen && $con_fiveteen<=7){
            $k=0.85*$heat;
        }elseif(7<$con_fiveteen && $con_fiveteen<=10){
            $k=0.8*$heat;
        }elseif(10<$con_fiveteen && $con_fiveteen<=13){
            $k=0.75*$heat;
        }elseif(13<$con_fiveteen){
            $k=0.70*$heat;
        }
        $everyheatstr = "每日膳食热量：".eval("return $k;")."  卡路里";
        array_push($data,$everyheatstr);
        /*$proportion = $con_fiveteen/$con_two*100;
        if($weight > $health  && $myIndex > 0){
            $conclusion = $name."，你好！根据你的测评，你的21天减重目标是".$con_fiveteen."kg，相当于现有体重的".number_format(eval("return $proportion;"),2)."%。研究显示，超重和肥胖患者体重如果能成功减轻5%-10%，可以提高多项身体健康指标，大大降低多种慢性疾病的患病风险。为了健康，为了美，请你加油哦。现在我们先来看看你的测评分析。";
            array_push($data,$conclusion);
        }
        if($weight < $health  && $myIndex > 0){
            $conclusion = $name."，你好！根据你的测评，你的21天减重目标是".$con_fiveteen." kg，超过了你的健康减重范围，我们建议尝试".$advinceweight." kg作为你的减重目标。为了健康，为了美，请你加油哦。现在我们先来看看你的测评分析。";
            array_push($data,$conclusion);
        }
        if(count($data)>=7){
            array_unshift($data, array_pop($data));
        }*/
        return $data;
    }


    /**获取相应题号的权重或者值
     * @param $answers
     * @param $index
     * @param $valueType
     * @return null
     */
    protected function getValue($answers,$index,$valueType){
        $value = null;
        foreach($answers as $k => $v){
            if($v['index'] == $index){
                $value = $answers[$k][$valueType];
            }
        }
        return $value;
    }


}
